/*************************************************************************
 * File Name:    Count_and_Say.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/16 17:03:49
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Count and Say
 |
 | The count-and-say sequence is the sequence of integers beginning as follows:
 | 1, 11, 21, 1211, 111221, ...
 |
 | 1 is read off as "one 1" or 11.
 | 11 is read off as "two 1s" or 21.
 | 21 is read off as "one 2, then one 1" or 1211.
 | Given an integer n, generate the nth sequence.
 | Note: The sequence of integers will be represented as a string.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

class Solution {
public:
    string countAndSay(int n)
    {
        string ans, t;
        size_t j, k;
        ostringstream tstream;
        
        ans = "1";
        for (int i = 1; i < n; ++i) {
            tstream.str("");
            for (j = 0; j < ans.size(); ++j) {
                for (k = j + 1; k < ans.size(); ++k) {
                    if (ans[k] != ans[j]) break;
                }
                tstream << k - j << ans[j];
                j = k - 1;
            }
            ans = tstream.str();
        }
        return ans;
    }
};

